package org.courierframework.core.handler.support;

import org.courierframework.core.handler.PaginationHandler;
import org.courierframework.core.repository.PaginationRepository;
import org.courierframework.core.search.Pagination;
import org.courierframework.core.search.Searchable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * @author long.shiyu
 * @since 1.7
 */
public abstract class JpaHandler<T, ID extends Serializable> implements PaginationHandler<T, ID> {
    /**
     * use spring 4.x generic autowired
     */
    @Autowired
    protected PaginationRepository<T, ID> paginationRepository;

    public void delete(ID id) {
        paginationRepository.delete(id);
    }

    public void delete(ID[] ids) {
        paginationRepository.delete(ids);
    }

    public void persist(T entity) {
        paginationRepository.persist(entity);
    }

    public void merge(T entity) {
        paginationRepository.merge(entity);
    }

    public T findOne(ID id) {
        return paginationRepository.findOne(id);
    }

    public List<T> findByJPQL(String jpql, Object... prams) {
        return paginationRepository.findByJPQL(jpql, prams);
    }

    public Pagination<T> findBySearch(Searchable<T> searchable) {
        //get total records
        Long recordsTotal = paginationRepository.findTotalRecords(searchable);
        //get filtered records
        Long recordsFiltered = paginationRepository.findFilteredRecordsBySearch(searchable);
        //get result by query conditions
        List<T> data = paginationRepository.findDataBySearch(searchable);
        //package data to Pagination
        return new Pagination<>(searchable.getDraw(), recordsTotal, recordsFiltered, data);
    }
}
